package models;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.TableGenerator;

import com.avaje.ebean.Ebean;
import com.avaje.ebean.annotation.EnumValue;

import play.db.ebean.Model;

@Entity
@Table(name = "token_actions")
public class TokenAction extends Model {
	
	private static final long serialVersionUID = 1L;
	
	public enum Type {
		@EnumValue("EV")
		EMAIL_VERIFICATION, @EnumValue("PR")
		PASSWORD_RESET
	}
	
	private final static long VERIFICATION_TIME = 7 * 24 * 3600;
	
	@Column(name = "id")
	@GeneratedValue(generator = "SEQ_TABLE", strategy = GenerationType.TABLE)
	@Id
	@TableGenerator(name = "SEQ_TABLE")
	private long id;
	
	@Column(name = "user")
	@ManyToOne
	private User targetUser;
	
	@Column(name = "type")
	private Type type;
	
	@Column(name = "token", unique = true)
	private String token;
	
	@Column(name = "created")
	private Date created;
	
	@Column(name = "expires")
	private Date expires;
	
	public static final Finder<Long, TokenAction> find = new Finder<Long, TokenAction>(long.class, TokenAction.class);
	
	public static TokenAction findByToken(Type type, String token) {
		return find.where().eq("type", type).eq("token", token).findUnique();
	}
	
	public static void deleteByUser(User user, Type type) {
		Ebean.delete(find.where().eq("user.id", user.getIdentifier()).eq("type", type).findList());
	}
	
	public boolean isValid() {
		return expires.after(new Date());
	}
	
	public static TokenAction create(User user, Type type, String token) {
		TokenAction action = new TokenAction();
		action.targetUser = user;
		action.type = type;
		action.token = token;
		Date currentDate = new Date();
		action.created = currentDate;
		action.expires = new Date(currentDate.getTime() + VERIFICATION_TIME * 1000);
		action.save();
		return action;
	}
	
}
